package Lee_code;

import java.util.HashSet;

public class Lee_1020
{
    int row, column, count;
    public int numEnclaves(int[][] grid)
    {
        row = grid.length;
        column = grid[0].length;
        boolean[][] seen = new boolean[row][column];
        for(int i=0; i<row; i++)
        {
            dfs(i,0,grid,seen);
        }
        for(int i=0; i<row; i++)
        {
            dfs(i,column-1,grid,seen);
        }

        for(int i=0; i<column; i++)
        {
            dfs(0,i,grid,seen);
        }
        for(int i=0; i<column; i++)
        {
            dfs(row-1,i,grid,seen);
        }

        for(int i=0; i<row; i++)
        {
            for(int j=0; j<column; j++)
            {
                if (grid[i][j] == 1)
                    count++;
            }
        }
        return count;
    }

    private void dfs(int i, int j, int[][] grid, boolean[][] seen)
    {
        //出界了
        if(i<0||j<0||i>=row||j>=column||seen[i][j]||grid[i][j]==0)
        {
            return;
        }
        seen[i][j] = true;
        grid[i][j] = 0;
        dfs(i+1, j, grid, seen);
        dfs(i-1, j, grid, seen);
        dfs(i, j+1, grid, seen);
        dfs(i, j-1, grid, seen);
    }
}
